<template>
  <el-dialog
    v-model="visible"
    title="上传图标"
    width="600px"
    @close="resetForm"
  >
    <el-form ref="taskFormRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item
        label="上传图标"
        prop="file"
        :rules="[{ required: true, message: '请上传图片', trigger: 'change' }]"
      >
        <el-upload
          v-model:file-list="fileList"
          action="#"
          :auto-upload="false"
          :on-remove="handleRemove"
          :limit="1"
          :multiple="false"
          :on-exceed="handleExceed"
          :on-change="handleChange"
          list-type="picture-card"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm">
        确认
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import type {
  FormInstance,
  FormRules,
  UploadProps,
  UploadFiles,
  UploadFile
} from "element-plus";
// 假设你已在 API 中实现了图片上传接口，将其方法名称改为 uploadServiceTypeImage
import { uploadServiceTypeIcon } from "@/api/adminServiceTypeApi";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

interface TaskForm {
  code: string;
  file: UploadFile | null;
}

const loading = ref(false);

const emits = defineEmits(["refresh"]);
const visible = ref(false);

// 初始化表单数据，code 为外部传入
const form = reactive<TaskForm>({
  code: "",
  file: null
});

// 表单验证规则
const rules: FormRules = {
  file: [{ required: true, message: "请上传图片", trigger: "change" }]
};

const taskFormRef = ref<FormInstance>();
const fileList = ref<UploadFiles>([]);

// 处理文件选择，限制上传的文件格式为图片
const handleChange: UploadProps["onChange"] = (file, fileListParam) => {
  const allowedExtensions = ["jpg", "jpeg", "png", "gif"];
  const ext = file.name.split(".").pop()?.toLowerCase();
  if (!ext || !allowedExtensions.includes(ext)) {
    ElMessage.error("仅支持 jpg、jpeg、png、gif 格式的图片");
    // 清空文件列表并将 form.file 置为空
    fileList.value = [];
    form.file = null;
    return;
  }
  form.file = file;
  fileList.value = fileListParam;
};

// 文件删除时清空对应数据
const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  form.file = null;
  fileList.value = uploadFiles;
};

// 超出上传数量时的提示
const handleExceed = (files: File[]) => {
  ElMessage.error("只能上传一张图片");
};

// 重置表单，清空文件列表
const resetForm = () => {
  taskFormRef.value?.resetFields();
  fileList.value = [];
};

// 表单提交，调用图片上传接口
const submitForm = () => {
  taskFormRef.value?.validate(async valid => {
    if (valid) {
      loading.value = true;
      try {
        // 这里假设图片接口接收 code 和图片文件的原始数据
        await uploadServiceTypeIcon(form.code, form.file!.raw);
        emits("refresh");
        visible.value = false;
      } catch (error) {
        console.error("图片上传失败", error);
      } finally {
        loading.value = false;
      }
    }
  });
};

// 外部调用打开弹窗，传入对应的 code 值
const open = (code: string) => {
  form.code = code;
  visible.value = true;
};

defineExpose({
  open
});
</script>
